/**
 * Created by zengy on 2017/6/8.
 */
angular.module('mainApp.appointment',['ui.router'])
    .config(function ($stateProvider) {
        $stateProvider
            .state({
            name: 'appointment/expert_meeting',
            url: '/appointment/expert_meeting',
            templateUrl: 'views/appointment/expert_meeting.html?v='+new Date().getMinutes(),
            controller: 'expertMeetingCtrl'
            })
            .state({
                name: 'appointment/tel_consultation',
                url: '/appointment/tel_consultation/:status',
                templateUrl: 'views/appointment/tel_consultation.html?v='+new Date().getMinutes(),
                controller: 'telConsultationCtrl'
            })
            .state({
                name: 'appointment/situation_description',
                url: '/appointment/situation_description/:orderId/:other',
                templateUrl: 'views/appointment/situation_description.html?v='+new Date().getMinutes(),
                controller: 'situationDescriptionCtrl'
            })
    })
    //专家见面
    .controller('expertMeetingCtrl',function ($scope) {
        $scope.$emit('arg',3);
        //专家见面列表
        var date=new Date();
        $scope.expertModel={
            pageNo:1,   //查询页数
            pageSize:10, //每页数条数
            startTimeRange:  date.getFullYear() + "-" + (date.getMonth())+ "-" + date.getDate(),
            endTimeRange:  date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate()
        }
        $scope.pagination = function (currentPage, pageCount) {
            $('.page-function #pagination').remove();
            $('.page-function').html('<ul id="pagination" class="pagination"></ul>');
            $('.pagination').twbsPagination({
                totalPages: pageCount,
                startPage: currentPage,
                visiblePages: 5,
                first: "首页",
                prev: "上一页",
                next: "下一页",
                last: "尾页",
                href: 'javascript:;',
                //hideOnlyOnePage : true,
                onPageClick: function (event, page) {
                    $scope.getExpertList(page)
                }
            });
        };
        $scope.getExpertList=function (page) {
            if(page){
                $scope.expertModel.pageNo=page;
                $scope.expertModel.pageSize=10;
            }
            if(!$scope.expertModel.startTimeRange && $scope.expertModel.endTimeRange){
                layer.msg('时间筛选不不符合规则！');
                return false;
            }
            if(parseInt(new Date($scope.expertModel.startTimeRange).getTime()/1000) > parseInt(new Date($scope.expertModel.endTimeRange).getTime()/1000)){
                layer.msg('开始时间不能大于结束时间！');
                return false;
            }
            layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
            new HttpRequest().getExpertConsultationList($scope.expertModel, function (res) {
                layer.closeAll();
                if (res.code == '000') {
                    $scope.expertList = res.data.list;
                    $scope.$apply();
                    if ($scope.expertList.length > 0) {
                        $scope.pagination($scope.expertModel.pageNo, res.data.pageCount);
                    }
                } else {
                    layer.msg('获取专家见面列表失败！')
                }
            })
        }
        $scope.getExpertList($scope.expertModel.pageNo);
        //重置
        $scope.reset=function () {
            $scope.expertModel={
                pageNo:1,   //查询页数
                pageSize:10, //每页数条数
                startTimeRange:null,
                endTimeRange:  null,
                userName:null,
                reservationStatus:null
            }
            $scope.getExpertList($scope.expertModel.pageNo);
        }
        //专家见面数据导出
        $scope.expertExcel=function () {
            delete $scope.expertModel.pageNo;
            delete $scope.expertModel.pageSize;
            if(!$scope.expertModel.startTimeRange && $scope.expertModel.endTimeRange){
                layer.msg('时间筛选不不符合规则！');
                return false;
            }
            if(parseInt(new Date($scope.expertModel.startTimeRange).getTime()/1000) > parseInt(new Date($scope.expertModel.endTimeRange).getTime()/1000)){
                layer.msg('开始时间不能大于结束时间！');
                return false;
            }
            new HttpRequest().expertMeetingExcel($scope.expertModel,function (res) {
                if(res.code='000'){
                    location.href=baseUrl+res.data;
                }else{
                    layer.msg('导出失败！');
                }
            })

        }

        $scope.conversation=function (event) {
            var _this=$(event.target);
            var dataDetail=_this.data('detail');
            var userName=dataDetail.userName;
            var cellPhone=dataDetail.cellPhone;
            var orderNo=dataDetail.orderNo;
            var index=layer.confirm('与'+userName+'联系<br />联系电话'+cellPhone,{
                title:'通话',
                btn: ['确定','取消'] ,//按钮
            },function () {
                layer.closeAll();
                new HttpRequest().customServiceCalling({orderNo: orderNo,toMobile:cellPhone},function (res) {
                    if(res.code !='000'){
                        layer.msg('操作失败！');
                    }else{
                        layer.msg('拨打中。。。');
                    }
                })
            },function () {
                layer.close(index)
            })
        }

        //$scope.dateStr=date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
        //$scope.day=getDayStr($scope.dateStr);
        // $scope.setDay=function () {
        //     $scope.day=getDayStr($scope.dateStr);
        // }
        $scope.reconversation=function (event) {
            var _this=$(event.target);
            var dataDetail=_this.data('detail');
            var dateStr=date.getFullYear()+"-"+dataDetail.expectTime.split(' ')[0].replace(/([^\u0000-\u00FF])/g,'-').replace(/-$/,'');
            var p=dataDetail.expectTime.split(' ')[1].slice(2,4);

                if(p=='上午'){
                    $('select[name="p"]').find('option[value="0"]').prop('selected',true)
                }else if(p=='下午'){
                    $('select[name="p"]').find('option[value="1"]').prop('selected',true)
                }else{
                    $('select[name="p"]').find('option[value="2"]').prop('selected',true)
                }
            //alert(dateStr)
            $scope.dateStr=dateStr
            $scope.day=getDayStr($scope.dateStr);
            $scope.setDay=function () {
                $scope.day=getDayStr($scope.dateStr);
            }
            var index1=layer.confirm('确定时间',{
                type: 1,
                title:'重新预约',
                area: ['420px', '200px'], //宽高
                content: $('#selectDay'),
                btn:['确定','取消']
            },function () {
                var reDate=$('#selectDay input').val();
                var periodTime=$('#selectDay select').val();
                var strDate="";
                if(periodTime=='0'){
                    strDate=reDate+' 12:00:00'
                }else if(periodTime=='1'){
                    strDate=reDate+' 18:00:00'
                }else{
                    strDate=reDate+' 22:00:00'
                }
                if(new Date(strDate).getTime()< date.getTime()){
                    layer.msg('预约时间不能小于当前时间！');
                    return false;
                }
                new HttpRequest().reReservationConsultation({rowId:dataDetail.rowId,schedualId:dataDetail.schedualId,date:reDate,periodTime:periodTime},function (res) {
                    if(res.code=='000'){
                        location.reload();
                    }else if(res.code=='1-004'){
                        layer.msg(res.data,function () {
                            layer.closeAll();
                        })
                    }
                        else{
                        layer.msg('操作失败',function () {
                            layer.closeAll();
                        })
                    }
                })

            },function () {
               layer.close(index1);
            });
        }
        $('.date-picker').datepicker({
            autoclose: true,
            changeMonth: true,
            language : 'zh-CN',
            format : 'yyyy-mm-dd',
            })
        // $('.date-picker[name="doctorTime"]').datepicker({
        //     autoclose: true,
        //     changeMonth: true,
        //     language : 'zh-CN',
        //     format : 'yyyy-mm-dd',
        //
        //     showOptions: {direction: 'down'}
        // })

        function getDayStr(d) {
            var str=""
            switch (new Date(d).getDay()){
                case 0:
                    str='星期日';
                    break
                case 1:
                    str='星期一';
                    break
                case 2:
                    str='星期二';
                    break
                case 3:
                    str='星期三';
                    break
                case 4:
                    str='星期四';
                    break
                case 5:
                    str='星期五';
                    break
                case 6:
                    str='星期六';
                    break
            }
            return str;
        }




    })
    //电话咨询
    .controller('telConsultationCtrl',function ($scope,$stateParams) {
        $scope.$emit('arg',3);
        var date=new Date();
        $('.date-picker').datepicker({
            autoclose: true,
            changeMonth: true,
            language : 'zh-CN',
            format : 'yyyy-mm-dd',
        })


        $scope.callModel={
            pageNo:1,
            pageSize:10,
            begintime:  date.getFullYear() + "-" + (date.getMonth()) + "-" + date.getDate(),
            endtime:  date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate(),
            status:$stateParams.status || ""
        }

        //重置
        $scope.reset=function () {
            $scope.callModel={
                pageNo:1,   //查询页数
                pageSize:10, //每页数条数
                begintime:null,
                endtime:  null,
                userName:null,
                status:null
            }
            $scope.queryCommentList($scope.callModel.pageNo)
        }
        $scope.dataDetail={};
        //分页
        $scope.pagination = function (currentPage, pageCount) {
            $('.page-function #pagination').remove();
            $('.page-function').html('<ul id="pagination" class="pagination"></ul>');
            $('.pagination').twbsPagination({
                totalPages: pageCount,
                startPage: currentPage,
                visiblePages: 5,
                first: "首页",
                prev: "上一页",
                next: "下一页",
                last: "尾页",
                href: 'javascript:;',
                //hideOnlyOnePage : true,
                onPageClick: function (event, page) {
                    $scope.queryCommentList(page)
                }
            });
        };
        //电话咨询列表
        $scope.queryCommentList=function (page) {
            if(page){
                $scope.callModel.pageNo=page;
                $scope.callModel.pageSize=10;
            }
            if(!$scope.callModel.begintime && $scope.callModel.endtime){
                layer.msg('时间筛选不不符合规则！');
                return false;
            }
            if(parseInt(new Date($scope.callModel.begintime).getTime()/1000) > parseInt(new Date($scope.callModel.endtime).getTime()/1000)){
                layer.msg('开始时间不能大于结束时间！');
                return false;
            }
            layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
            new HttpRequest().queryCommentList($scope.callModel, function (res) {
                layer.closeAll();
                if (res.code == '000') {
                    $scope.callList = res.data.list || [];
                    $scope.$apply();
                    if ($scope.callList.length > 0) {
                        $scope.pagination($scope.callModel.pageNo, res.data.pageCount);
                    }
                } else {
                    layer.msg('获取电话咨列表失败！')
                }
            })
        }
        //导出电话咨询
        $scope.exportExcel=function () {
            if(!$scope.callModel.begintime && $scope.callModel.endtime){
                layer.msg('时间筛选不不符合规则！');
                return false;
            }
            if(parseInt(new Date($scope.callModel.begintime).getTime()/1000) > parseInt(new Date($scope.callModel.endtime).getTime()/1000)){
                layer.msg('开始时间不能大于结束时间！');
                return false;
            }
            new HttpRequest().telConsultationExcel($scope.callModel,function (res) {
                if(res.code=='000'){
                    location.href=baseUrl+res.data;
                    //location.href=baseUrl.slice(0,baseUrl.length-1)+res.data.split('?')[0]+'?'+res.data.split('?')[1].replace(/{/g,"%7B").replace(/}/g,"%7D")
                }else{
                    layer.msg('操作失败！');
                }
            })
            
        }
        $scope.queryCommentList($scope.callModel.pageNo)
        //通话记录
        $scope.conversationList=function (event) {
            var _this=$(event.target);
            var orderNo=_this.attr('data-orderNo');
            new HttpRequest().queryMobileLog({orderNo:orderNo},function (res) {
                if(res.code =='000'){
                    var conList=res.data || [];
                    var html='';
                    conList.map(function (index) {
                        html+= index.createTime+'，'+index.callStaus+':'+index.callTime+'秒<br />';
                    });
                    if(html){
                        layer.open({
                            title:'通话记录',
                            type: 1,
                            area: ['420px', '240px'],
                            content: html
                        });
                    }else{
                        layer.msg('暂无通话记录')
                    }

                }else{
                    layer.msg('获取失败！')
                }
            })
        }
        //通话步骤 拨打患者电话

        $scope.callUser=function (event) {
            var _this=$(event.target);
            var dataDetail=_this.closest('.callPhone').data('detail');
            $scope.dataDetail= dataDetail;
            layer.confirm('与'+dataDetail.userName+'联系<br />电话'+ $scope.dataDetail.userMobile, {
                title:'拨打电话',
                btn: ['确认拨打','取消拨打'] //按钮
            }, function(){
                layer.closeAll();
                new HttpRequest().customServiceCalling({orderNo: $scope.dataDetail.orderNo,toMobile: $scope.dataDetail.userMobile},function (res) {
                    if(res.code =!'000'){
                       layer.msg('通话失败！');
                    }else{
                        layer.msg('拨打中。。。')
                    }
                })
            }, function(){
               layer.closeAll();
            });
        }
        //客服拨打医生电话
        $scope.callDoctor=function () {
            var _this=$(event.target);
            var dataDetail=_this.closest('.callPhone').data('detail');
            $scope.dataDetail= dataDetail;
            $('#secend .doctor-name').html('与'+$scope.dataDetail.doctorName+'联系');
            $('#secend .doctor-tel').html('联系电话'+$scope.dataDetail.doctorMobile);
            var index = layer.open({
                title:'确认通话',
                type: 1,
                area: ['420px', '260px'], //宽高
                content: $('#secend')
            });

        }
        //确认拨打医生电话
        var flag=false;
        $scope.Call=function (event) {
            var _this=$(event.target);
            $('#secend .choose-time').show();
            $scope.minDate=date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
            _this.attr('disabled','disabled');
            new HttpRequest().customServiceCalling({orderNo: $scope.dataDetail.orderNo,toMobile: $scope.dataDetail.doctorMobile},function (res) {
                if(res.code =!'000'){
                    layer.msg('通话失败！');
                    flag=false;
                }else{
                    flag=true;
                }
            })
        }
        //取消拨打
        $scope.cancelCall=function () {
            layer.closeAll();
        }
        //时间更改保存
        $scope.save=function () {
            var time=$('input[name="doctorTime"]').val();
            var hour=$('select.doctor-hour').val();
            var sec=$('select.doctor-sec').val();
            var consultationTime=time+' '+hour+':'+sec+':00';
            if(new Date(consultationTime).getTime()< date.getTime() && !false){
                layer.msg('预约时间不能小于当前时间！');
                return false;
            }
            new HttpRequest().updateMobileServiceTime({wxOpenId:$scope.dataDetail.wxOpenId,orderNo: $scope.dataDetail.orderNo,consultationTime:consultationTime,mobileServiceId:$scope.dataDetail.mobileServiceId},function (res) {
                if(res.code == '000' && res.data=='1'){
                    location.reload();
                }else{
                    layer.msg('预约失败！');
                }
            })
        }
        //双向拨打
        $scope.callDouble=function () {
            var _this=$(event.target);
            var dataDetail=_this.closest('.callPhone').data('detail');
            $scope.dataDetail= dataDetail;
            layer.confirm('接通',{
                type: 1,
                title:'接通',
                area: ['300px', '210px'], //宽高
                content: '<div style="padding: 10px;">'+
                '<p>用户'+$scope.dataDetail.userName+'('+$scope.dataDetail.userMobile+')</p>'+
                '<p>与</p>'+
                '<p>医生'+$scope.dataDetail.doctorName+'('+$scope.dataDetail.doctorMobile+')</p>'+
                '</div>',
                btn: ['确认拨打', '取消拨打']
            },function () {

                new HttpRequest().doubleTalk({orderNo:$scope.dataDetail.orderNo ,wxOpenId:$scope.dataDetail.wxOpenId},function (res) {
                    if(res.code !='200' && res.data !='200'){
                        layer.msg('双向通话失败！')
                    }
                })
            },function () {
                layer.closeAll();

            });
        }


        //重新预约
        $scope.retime={};
        $scope.reconversation=function(event){
            var _this=$(event.target);
            var mobileServiceId=_this.attr('data-mobileServiceId');
            var orderNo=_this.attr('data-orderNo');
            var wxOpenId=_this.attr('data-wxOpenId');
            var orderTime= + _this.attr('data-ordertime');
            if(orderTime){
                var year=new Date(orderTime).getFullYear();
                var month=new Date(orderTime).getMonth()+1;
                var day=new Date(orderTime).getDate();
                var hour=(new Date(orderTime).getHours() < 10 ? '0'+new Date(orderTime).getHours() : new Date(orderTime).getHours());
                var min=(new Date(orderTime).getMinutes() < 10 ? '0'+new Date(orderTime).getMinutes() : new Date(orderTime).getMinutes());
                if(parseInt(hour)<9){
                    $('select.hour').find("option[value='08']").prop("selected",true);
                }else{
                    $('select.hour').find("option[value='"+hour+"']").prop("selected",true);
                }
                $('select.sec').find("option[value='"+min+"']").prop("selected",true);
                $scope.orderTime=year+'-'+month+'-'+day;
            }else{
                $scope.orderTime=date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate();
            }



            $scope.retime={
                orderNo:orderNo,
                mobileServiceId:mobileServiceId,
                wxOpenId:wxOpenId
            }
        }
        $scope.commitReTime=function () {
            var time=$('input[name="date"]').val();
            var hour=$('select.hour').val();
            var sec=$('select.sec').val();
            var consultationTime=time+' '+hour+':'+sec+':00';
            if(new Date(consultationTime).getTime()< date.getTime() && !false){
                layer.msg('预约时间不能小于当前时间！');
                return false;
            }
            console.log(consultationTime);
            $scope.retime.consultationTime=consultationTime;
            new HttpRequest().updateMobileServiceTime($scope.retime,function (res) {
                if(res.code !='000' && data !=='1'){
                    layer.msg('修改失败！');
                    layer.closeAll();
                }else{
                    location.reload();
                }
            })

        }


    })
    //详细情况
    .controller('situationDescriptionCtrl',function ($scope,$stateParams,$location) {
        $scope.orderId=$stateParams.orderId;
        if( $stateParams.other){
            $('.main-header,.main-sidebar').hide();
            $('.content-wrapper .detail .footer').hide();
            $('.detail').css({'width':'90%','overflow':'hidden','marging':'0 12px'})
        }
        if(!$scope.orderId){
            $state.go('appointment/tel_consultation');
            return false;
        }
        new HttpRequest().getPatientDetailOfPhoneConsult({orderId:$scope.orderId},function (res) {
            $('body').addClass('show');
            if(res.code=='000'){
                if($stateParams.other){
                    document.title=res.data.userName+'病情描述';
                }

                $scope.callDetail=res.data;
                $scope.$apply();
            }else{
                layer.msg('获取失败！');
            }
        })
      //生成二维码
        var qrcode = new QRCode(document.getElementById("qrcode"), {
            width : 120,//设置宽高
            height : 120
        });
        console.log($location.absUrl());
        qrcode.makeCode( $location.absUrl()+'other');




    })

    .directive('repeatDesignPageFinish',function(){
        return {
            link: function(scope){
                if(scope.$last){

                }
            }
        }
    })
